#coding:utf8
from config import *
from config_mouse_start import *

to_lock = threading.Lock()
xing_q = deque([], 3)
def get_screen_indx(x,y):
    for i in range(len(screen_config_for_indx)):
        con = screen_config_for_indx[i]
        if x>=con[0] and y>=con[1] and x<=con[2] and y<= con[3]:
            return i
    return 0

def is_in_cur_screen(x, y):    
    i =  get_screen_indx(cfg.fix_pos[0], cfg.fix_pos[1])
    sx, sy, ex, ey =   screen_config[i]    
    if x >= sx and x <= ex and y >= sy and y <= ey:
        return True
    return False

def is_in_all_screen(x, y):
    for i in screen_config:
        sx, sy, ex, ey = i
        if x >= sx and x <= ex and y >= sy and y <= ey:
            return True
    return False
def is_in_screen(x, y):    
    for i in screen_config:
        sx, sy, ex, ey = i
        if x >= sx and x <= ex and y >= sy and y <= ey:
            return True
    return False

def is_sca():
    return cfg.sca != 0 or  cfg.sca_du != 0 or  cfg.sca_cur != 0  

def deal_xing_q():
    global xing_q
    xing_q.append(time.time())
    if len(xing_q) == 3 and xing_q[-1] - xing_q[0] < 0.8:        
        cfg.show_mouse_tip = False        
        clear(True)
        print('xing clear')
        
def x2_d_to_dst():
    dx = (cfg.snap[-1][1] -  cfg.snap[0][1]) * cfg.x2_mode_d / 100 + cfg.snap[0][1]
    dy = (cfg.snap[-1][2] -  cfg.snap[0][2]) * cfg.x2_mode_d / 100 + cfg.snap[0][2]
    cfg.x2_mode_dst = (round(dx), round(dy))

def getdu(mouse_pos=None):
    x, y = get_cur_pos()
    if mouse_pos:
        x, y = mouse_pos
    sx, sy = cfg.fix_pos
    dx = x - sx
    dy = y - sy
    du0 = math.atan2(dy, dx)
    s = sca_l[cfg.sca%len(sca_l)]
    d =  du0 -cfg.sca_cur
    if d >  math.pi:
        d -= 2 * math.pi
    if d < - math.pi:
        d += 2 * math.pi
    du = cfg.sca_du + d * s
    if is_sca():
        x, y = cfg.sca_cur_pos
        dx = x - sx
        dy = y - sy
    ll = math.sqrt(dx*dx+dy*dy)
    return du, ll

def getp(mouse_pos=None, doRound=True):
    du, ll = getdu(mouse_pos)
    sx, sy = cfg.fix_pos
    if doRound:
        return round(ll * math.cos(du) + sx), round(ll * math.sin(du) + sy)
    else:
        return ll * math.cos(du) + sx, ll * math.sin(du) + sy

def cal_mouse_d(sp):
    pos = get_cur_pos()
    dx = pos[0] - sp[0]
    dy = pos[1] - sp[1]
    return math.sqrt(dx*dx+dy*dy)

def cut_to(d):    
    if d > max_l:
        d =  max_l
    if d < 0:
        d = 0
    return d
    
def dotdot():    
    if cfg.isShow:
        cfg.isShow = False                
        cfg.show_one_on = False
        return
    
    if cfg.w2showing:        
        cfg.show_one_on = False
        return
    
    cfg.show_one_on = True
    cfg.show_one_onetime = True

def lock_add():    
    cfg.lock_step = min(cfg.lock_step + 1, len(lock_l) -1) 
    
def lock_min():    
    if cfg.lock_step == 0:        
        dotdot()
        return
    cfg.lock_step = max(0, cfg.lock_step - 1)
    
def lock_get():
    return lock_l[cfg.lock_step%len(lock_l)]


def find_near_d(digit=False):
    st,en = cfg.snap[0],cfg.snap[-1]    
    st = int(st[0])
    en = int(en[0])
    f = cfg.x2_mode_d*(en-st)/100+st
    if digit:
        f = '%.2f' % f
    else:
        f = round(f)
    cfg.sum = str(f)    

def deal_x2_mode_num():
    st,en = cfg.snap[0],cfg.snap[-1]
    print('deal x2',st,en)
    st = int(st[0])
    en = int(en[0])
    if en-st<=0:
        return        
    f = float(cfg.sum)
    if f<st or f>en:
        return            
    cfg.x2_mode_d = (f-st)*100/(en-st)
    x2_d_to_dst()

def on_click2(x, y, button, pressed,deal_x):
    cfg.last_active_time = time.time()
    print('click',x,y, button,pressed, deal_x)
    if cfg.x2_mode and 'x1' not  in str(button) and 'x2' not  in str(button):
        cfg.x2_mode = False
        
    if (False or deal_x) and ('x1' in str(button) or 'x2' in str(button)):
        if pressed:            
            if not cfg.x2_pressed:
                cfg.x2_pressed = True
                cfg.x2_pressed_then_other = False
            else:
                cfg.x2_pressed_then_other = True
                cfg.showCut = not cfg.showCut
        if not pressed:
            cfg.x2_pressed =False
            if not cfg.x2_pressed_then_other:
                if 'x1' in str(button):
                    if cfg.x2_mode:
                        cfg.x2_mode = False
                        set_cfg_sum_0()
                        mouse.Controller().position = (cfg.x2_mode_dst[0],cfg.x2_mode_dst[1])
                        clear(True)
                        
                    else:
                        if cfg.sum !='0':
                            deal_e(True)
                            return
                        xing()                        
                        deal_xing_q()
                                                                        
                if 'x2' in str(button):
                    if cfg.x2_mode:
                        if cfg.x2_mode_d == 0:
                            cfg.x2_mode_d = 100
                        else:
                            cfg.x2_mode_d -= 50
                            if cfg.x2_mode_d < 0:
                                cfg.x2_mode_d = 0
                        find_near_d()
                        deal_x2_mode_num()
                    
                    elif cfg.sum != '0':
                        d = -round(float(cfg.sum))
                        deal_manu_scroll(d)
                        set_cfg_sum_0()                
                    elif cfg.min_ge!=0 and not cfg.min_ge_force_show and cfg.w2showing:
                        cfg.min_ge_force_show = True                                 

                    elif cfg.w2showing and not cfg.x2_mode:
                        a = get_snap_sort()                        
                        if len(a) == 0:
                            return
                        
                        if len(a) == 1:
                            set_cfg_sum_0()
                            mouse.Controller().position = (a[0][1],a[0][2] )
                            clear(True)
                            return
                        cfg.snap = a
                        cfg.x2_mode = True
                        cfg.x2_mode_start_pos = get_cur_pos()
                        cfg.x2_mode_d = 100
                        x2_d_to_dst()                    
                                                
                    else:
                        ori = cfg.min_ge
                        if not cfg.w2showing:
                            clear(True)
                            cfg.show_one_on = True
                            cfg.force_show = True                
                        ge_add_x2(ori)
            else:
                cfg.is_suo =False
        return
    
    if ('x1' in str(button) or 'x2' in str(button)):
        return
    
    if cfg.mouse_pressed and pressed:
        return
    
    if pressed:
        cfg.mouse_pressed = True
    else:
        cfg.mouse_pressed = False
        
    if cfg.isOn2:
        cfg.isShow = True
    else:
        cfg.isShow = False
    if cfg.always_show_one:      
        cfg.show_one_on = True
    else:
        cfg.show_one_on = False
    ori = cfg.force_show
    clear(True)
    if pressed:
        cfg.force_show = ori
       
def update_du(add):    
    du, ll = getdu()
    cfg.sca_du = du
    if add:
        cfg.sca += 1
    x, y = get_cur_pos()
    sx, sy = cfg.fix_pos
    dx = x - sx
    dy = y - sy
    cfg.sca_cur = math.atan2(dy, dx)
    cfg.sca_cur_pos = (x, y)

def deal_manu_scroll(d):    
    cfg.manu_add = d
    
def get_num():
    if '0.' == cfg.sum[0:2]:
        d = -int(cfg.sum.replace('0.', '') )
    else:
        d = round(float(cfg.sum))
    return d

def xing():    
    if cfg.sum != '0':
        if '0.0' in cfg.sum:
            cfg.force_scroll = not cfg.force_scroll
            set_cfg_sum_0()
            return
        
        if '0.' == cfg.sum[0:2] and cfg.sum!='0.':
            d = int(cfg.sum.replace('0.', '') )
            cfg.fix_scroll = d
            set_cfg_sum_0()
            return
        if '.' == cfg.sum[-1]:
            d = int(cfg.sum.replace('.', '') )
            cfg.fix_scroll = d
            set_cfg_sum_0()
            return
        
        d = round(float(cfg.sum))
        deal_manu_scroll(d)        
        set_cfg_sum_0()
        return
    
    oriIsshow = cfg.isShow
    cfg.isShow = False
    ori = cfg.force_show
    clear(True)
    if cfg.w2showing or oriIsshow:
        cfg.show_one_on = False
        return
    
    if not cfg.show_one_on:
        cfg.show_one_on = True
        cfg.force_show = True
        return
    if ori:
        cfg.show_one_on = False
        cfg.force_show = False
        return
    cfg.force_show = True

def deal_reset_one():
    if cfg.always_show_one:
        if cfg.reset_show_one:
            cfg.show_one_on = False
        else:
            cfg.show_one_on = True    

def get_snap_sort():
    a = copy.deepcopy(cfg.w2snap)
    if len(a) == 0:
        return []
    
    a = sorted(a,key=lambda x: int(x[0]))                        
    max_idx = 0
    for i in range(len(a)):
        if is_in_screen(a[i][1], a[i][2]):
            max_idx = i
    print('max_idx', max_idx)
    return a[0:max_idx+1]

def ctrl2():
    if not cfg.w2showing:
        return
    
    a = get_snap_sort()
    if len(a) > 0:
        set_cfg_sum_0()
        mouse.Controller().position = (a[-1][1], a[-1][2])
        clear(True)

def deal_e_get(dx,dy):
    a,f = change_sum(cfg.sum)
    if not a:
        f = -f
    if dx!=0 or dy!=0:
        cfg.last_m = (dx,dy)
        dx = round(dx*f + dx)
        dy = round(dy*f + dy)
        return dx,dy    
    
    dx,dy = cfg.last_m
    dx = round(dx*f)
    dy = round(dy*f)
    return dx,dy

def move_and_set_fix(x,y):
    cfg.fix_pos =  (x, y)    
    s = cfg.sum
    clear(False)
    mouse.Controller().position = (x, y)    
    cfg.sum = s

def xuan_get_du():
    a,b = change_sum(cfg.sum)
    if b==0:
        if a:
            return 15
        return 7.5
    return b

def deal_xuan(mode):
    if mode==0:
        return 
    
    if is_sca():
        return
    if not cfg.w2showing:
        return
    if cfg.x2_mode:
        return
    b = xuan_get_du()
    if mode==1:
        b = -b

    x2,y2 = get_cur_pos()
    x1,y1 = cfg.fix_pos
    d = math.atan2((y1-y2),(x1-x2))
    ll = cal_dis((x1,y1),(x2,y2))
    d2 = d+b*math.pi/180
    cfg.fix_pos = (round(ll*math.cos(d2))+x2,round(ll*math.sin(d2))+y2 )    

def deal_e(pos_check,mode=0):          
    if is_ff(cfg.sum):
        deal_xuan(mode)
        set_cfg_sum_0()
        return
    
    x, y = getp(None, False)
    sx, sy = cfg.fix_pos
    dx = x - sx
    dy = y - sy
    if str(cfg.sum)=='0':        
        cfg.last_m = (dx,dy)
        clear(True)
        cfg.show_one_on = True
        return
    dx,dy = deal_e_get(dx,dy)        
    move_and_set_fix(sx + dx, sy + dy)
    set_cfg_sum_0()
    if pos_check:
        cfg.set_fix_time = time.time()
    
    deal_reset_one()     

def deal_add():    
    if cfg.min_ge!=0 and not cfg.min_ge_force_show:
        cfg.min_ge_force_show = True
        return
    
    cfg.min_ge = 0
    cfg.w2_last_ge = 0
    cfg.w2_last_to = 0
    cfg.w2_last_dis = 0
    cfg.last_ge = 0
    cfg.w2_min_ge = 0
    cfg.to = 0
    if cfg.sum == '0':
        if cfg.isShow:
            cfg.isShow = False
            cfg.show_one_on = True
        else:
            cfg.isShow = True        
        return
    deal_e(True,1)

def do_step_move(x,y):    
    if not cfg.w2showing:
        if cfg.min_ge!=0 or cfg.force_show:
            cfg.show_one_on =True
            cfg.show_one_onetime = True
        else:    
            cfg.show_one_on = False
    mouse.Controller().move(x,y)

def deal_lock(a):    
    print('lock', a)    
    if a == 10:
        lock_min()
    if a == 5:
        lock_add()
    if a == 0:
        lock_step_clear()
    if a in arrm:
        dx, dy = arrm[a]        
        do_step_move(dx*lock_get(), dy*lock_get())        
        cfg.lock_xing_last_move =  a
    
def deal_pressed():    
    if not cfg.is_pressed:
        mouse.Controller().press(mouse.Button.left)  
        cfg.is_pressed = True
    else:
        mouse.Controller().release(mouse.Button.left)
        cfg.is_pressed = False

def move_p(a):    
    a = str(a)
    print('move', a, cfg.pos_m)
    if type(cfg.pos_m) ==type({}) and a in cfg.pos_m:
        clear(False, False)
        cfg.fix_pos =  cfg.pos_m[a]    
        mouse.Controller().position = cfg.pos_m[a]
        deal_reset_one()  

def load_pos():    
    try:
        f = open(pos_json_path)
        cfg.pos_m = json.load(f)
        f.close()        
    except:
        cfg.pos_m = {}

def add_p(a):    
    a = str(a)
    load_pos()
    cfg.pos_m[a] = mouse.Controller().position
    print('pos', cfg.pos_m)
    try:
        f = open(pos_json_path, 'w')
        json.dump(cfg.pos_m, f, indent=4)
        f.close()        
    except Exception as e:
        print(e)
        
    print('add', a)    

def deal_set(st, a):    
    if a < 0:
        return False
    
    if a >= 0 and a <= 10:
        add_p(a)
        return False
    
    return False    
 